package com.jessechanrui.template.req1112;

import galaxy.ide.tech.cpt.Component;
import galaxy.ide.tech.cpt.ComponentGroup;
import galaxy.ide.tech.cpt.InParams;
import galaxy.ide.tech.cpt.Param;
import galaxy.ide.tech.cpt.Return;
import galaxy.ide.tech.cpt.Returns;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import tc.platform.P_DataBase;
import cn.com.agree.afa.jcomponent.DBConnProvider;
import cn.com.agree.afa.svc.javaengine.AppLogger;
import cn.com.agree.afa.svc.javaengine.TCResult;
import cn.com.agree.afa.svc.javaengine.context.JavaDict;
import cn.com.agree.afa.svc.javaengine.context.JavaList;

import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;



/**
 * pdf组件类
 * 
 * @date 2017-07-04 10:48:11
 */
@ComponentGroup(level = "银行", groupName = "pdf组件类")
public class B_wzyhPDFReport {
	
	
	
	/**
	 * @category pdf生成组件
	 * @return 1 成功<br/>
	 * @throws Exception 
	 */
	@InParams(param = {
			@Param(name = "__REQ__", comment = "请求数据容器", type = cn.com.agree.afa.svc.javaengine.context.JavaDict.class),
			@Param(name = "filePath", comment = "文件全路径", type = String.class),
			@Param(name = "fileName", comment = "文件名称", type = String.class),
			})
	@Returns(returns = { @Return(id = "0", desp = "失败"),
 			@Return(id = "1", desp = "成功") })
	@Component(label = "pdf生成组件", style = "处理型", type = "同步组件", author = "zhangli", date = "2019-01-24 03:11:51")
	public static TCResult B_wzyhPDFReport(JavaDict __REQ__,String filePath,String fileName){
		
		 File file = new File(filePath+fileName); 
	     try {
			file.createNewFile();
			new B_wzyhPDFReport(file).generatePDF();
		 } catch (Exception e) {
			 AppLogger.info("生成pdf失败");
			e.printStackTrace();
		 }
		 return TCResult.newSuccessResult();
	} 
           
	
	Document document = new Document();// 建立一个Document对象     
    
    private static Font headfont ;// 设置字体大小 
    private static Font keyfont;// 设置字体大小 
    private static Font textfont;// 设置字体大小 
       
   
       
    static{ 
        BaseFont bfChinese; 
        try { 
            bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED); 
            headfont = new Font(bfChinese, 10, Font.BOLD);// 设置字体大小 
            keyfont = new Font(bfChinese, 8, Font.BOLD);// 设置字体大小 
            textfont = new Font(bfChinese, 8, Font.NORMAL);// 设置字体大小 
        } catch (Exception e) {          
            e.printStackTrace(); 
        }  
    } 
       
       
    public B_wzyhPDFReport(File file) {         
         document.setPageSize(PageSize.A4);// 设置页面大小 
         try { 
            PdfWriter.getInstance(document,new FileOutputStream(file)); 
            document.open();  
        } catch (Exception e) { 
            e.printStackTrace(); 
        }  
           
           
    } 
    int maxWidth = 520; 
       
       
     public PdfPCell createCell(String value,com.lowagie.text.Font font,int align){ 
         PdfPCell cell = new PdfPCell(); 
         cell.setVerticalAlignment(Element.ALIGN_MIDDLE);         
         cell.setHorizontalAlignment(align);     
         cell.setPhrase(new Phrase(value,font)); 
        return cell; 
    } 
       
     public PdfPCell createCell(String value,com.lowagie.text.Font font){ 
         PdfPCell cell = new PdfPCell(); 
         cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 
         cell.setHorizontalAlignment(Element.ALIGN_CENTER);  
         cell.setPhrase(new Phrase(value,font)); 
        return cell; 
    } 
   
     public PdfPCell createCell(String value,com.lowagie.text.Font font,int align,int colspan){ 
         PdfPCell cell = new PdfPCell(); 
         cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 
         cell.setHorizontalAlignment(align);     
         cell.setColspan(colspan); 
         cell.setPhrase(new Phrase(value,font)); 
        return cell; 
    } 
    public PdfPCell createCell(String value,com.lowagie.text.Font font,int align,int colspan,boolean boderFlag){ 
         PdfPCell cell = new PdfPCell(); 
         cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 
         cell.setHorizontalAlignment(align);     
         cell.setColspan(colspan); 
         cell.setPhrase(new Phrase(value,font)); 
         cell.setPadding(3.0f); 
         if(!boderFlag){ 
             cell.setBorder(0); 
             cell.setPaddingTop(15.0f); 
             cell.setPaddingBottom(8.0f); 
         } 
        return cell; 
    } 
     public PdfPTable createTable(int colNumber){ 
        PdfPTable table = new PdfPTable(colNumber); 
        try{ 
            table.setTotalWidth(maxWidth); 
            table.setLockedWidth(true); 
            table.setHorizontalAlignment(Element.ALIGN_CENTER);      
            table.getDefaultCell().setBorder(1); 
        }catch(Exception e){ 
            e.printStackTrace(); 
        } 
        return table; 
    } 
     public PdfPTable createTable(float[] widths){ 
            PdfPTable table = new PdfPTable(widths); 
            try{ 
                table.setTotalWidth(maxWidth); 
                table.setLockedWidth(true); 
                table.setHorizontalAlignment(Element.ALIGN_CENTER);      
                table.getDefaultCell().setBorder(1); 
            }catch(Exception e){ 
                e.printStackTrace(); 
            } 
            return table; 
        } 
       
     public PdfPTable createBlankTable(){ 
         PdfPTable table = new PdfPTable(1); 
         table.getDefaultCell().setBorder(0); 
         table.addCell(createCell("", keyfont));          
         table.setSpacingAfter(20.0f); 
         table.setSpacingBefore(20.0f); 
         return table; 
     } 
        
     public void generatePDF() throws Exception{ 
        PdfPTable table = createTable(4); 
        table.addCell(createCell("学生信息列表：", keyfont,Element.ALIGN_LEFT,4,false)); 
               
        table.addCell(createCell("姓名", keyfont, Element.ALIGN_CENTER)); 
        table.addCell(createCell("年龄", keyfont, Element.ALIGN_CENTER)); 
        table.addCell(createCell("性别", keyfont, Element.ALIGN_CENTER)); 
        table.addCell(createCell("住址", keyfont, Element.ALIGN_CENTER)); 
           
        for(int i=0;i<30;i++){ 
            table.addCell(createCell("姓名"+i, textfont)); 
            table.addCell(createCell(i+15+"", textfont)); 
            table.addCell(createCell((i%2==0)?"男":"女", textfont)); 
            table.addCell(createCell("地址"+i, textfont)); 
        } 
        document.add(table); 
           
        document.close(); 
     }
     
     
     /**
  	 * @category txt2pdf组件 
  	 */
  	@InParams(param = {
  			@Param(name = "__REQ__", comment = "请求数据容器", type = cn.com.agree.afa.svc.javaengine.context.JavaDict.class),
  			@Param(name = "textPath", comment = "txt文件路径", type = String.class),
  			@Param(name = "pdfPath", comment = "pdf文件全路径", type = String.class),
  			})
 	@Returns(returns = { @Return(id = "0", desp = "失败"),
 			@Return(id = "1", desp = "成功") })
  	@Component(label = "txt2pdf组件", style = "处理型", type = "同步组件", author = "zhangli", date = "2019-02-25 03:11:51")     
      public static TCResult text2pdf(JavaDict __REQ__,String text, String pdf) throws com.lowagie.text.DocumentException, IOException  {
          Document document = new Document();
          OutputStream os;
 			os = new FileOutputStream(new File(pdf));
             PdfWriter.getInstance(document, os);
             document.open();
             InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(text)), "GBK");
             @SuppressWarnings("resource")
 			BufferedReader bufferedReader = new BufferedReader(isr);
             String str = "";
 			    while ((str = bufferedReader.readLine()) != null) {
 			        document.add(new Paragraph(str, keyfont));
 			    }
             document.close();
             return TCResult.newSuccessResult();
      }

     /**
 	 * @category pdf加章生成组件
 	 * @return 1 成功<br/>
 	 * @throws Exception 
 	 */
 	@InParams(param = {
 			@Param(name = "__REQ__", comment = "请求数据容器", type = cn.com.agree.afa.svc.javaengine.context.JavaDict.class),
 			@Param(name = "templatePath", comment = "模板文件路径", type = String.class),
 			@Param(name = "targetPath", comment = "生成的文件路径", type = String.class),
 			@Param(name = "imagePath", comment = "原图片路径", type = String.class),
 			@Param(name = "outfilepath", comment = "透明图片路径", type = String.class),
 			})
 	//@Returns(returns = { @Return(id = "1", desp = "成功") })
 	@Returns(returns = { @Return(id = "0", desp = "失败"),
 			@Return(id = "1", desp = "成功") })
 	@Component(label = "pdf加章生成组件", style = "处理型", type = "同步组件", author = "zhangli", date = "2019-01-24 03:11:51")
 	public static TCResult B_wzyhyzPDFReport(JavaDict __REQ__,String templatePath,String targetPath,String imagePath,String outfilepath) {
 		try {

        fillData(imagePath,outfilepath);
        // 读取模板文件
        FileInputStream input = new FileInputStream(new File(templatePath));        
        PdfReader reader = new PdfReader(input);
        int pages=reader.getNumberOfPages();
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(targetPath));
        Document document = new Document();
        // 通过域名获取所在页和坐标，左下角为起点
        float x = document.getPageSize().getWidth() - 200;
        float y = document.getPageSize().getHeight() - 800;
        // 读图片
        Image image = Image.getInstance(outfilepath);
        //PdfReader pdfReader=new PdfReader(templatePath);
		//int pages=pdfReader.getNumberOfPages();
        for(int i=1;i<=pages;i++){
            // 获取操作的页面
            PdfContentByte under = stamper.getOverContent(i);
            // 根据域的大小缩放图片
            image.scaleToFit(document.getPageSize().getWidth() - 420, document.getPageSize().getHeight() - 350);
            // 添加图片
            image.setAbsolutePosition(x, y);
            under.addImage(image);
        }
        stamper.close();
        reader.close();
 		} catch (Exception e) {
			 AppLogger.info("生成pdf失败");
			return TCResult.newFailureResult("0010",e.toString()+"加盖印章失败");
			
		 }
 		 return TCResult.newSuccessResult();
 	} 
 	private static void fillData(String inpath,String outpath) throws IOException{
        // BufferedImage image = ImageIO.read(new File("E:\\pdf\\123.png"));
 		BufferedImage image = ImageIO.read(new File(inpath));
         // 高度和宽度
         int height = image.getHeight();
         int width = image.getWidth();
         
         // 生产背景透明和内容透明的图片
         ImageIcon imageIcon = new ImageIcon(image);
         BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
         Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics(); // 获取画笔
         g2D.drawImage(imageIcon.getImage(), 0, 0, null); // 绘制Image的图片

         int alpha = 0; // 图片透明度
         // 外层遍历是Y轴的像素
         for (int y = bufferedImage.getMinY(); y < bufferedImage.getHeight(); y++) {
             // 内层遍历是X轴的像素
             for (int x = bufferedImage.getMinX(); x < bufferedImage.getWidth(); x++) {
                 int rgb = bufferedImage.getRGB(x, y);
                 // 对当前颜色判断是否在指定区间内
                 if (colorInRange(rgb)){
                     alpha = 0;
                 }else{
                     // 设置为不透明
                     alpha = 255;
                 }
                 // #AARRGGBB 最前两位为透明度
                 rgb = (alpha << 24) | (rgb & 0x00ffffff);
                 bufferedImage.setRGB(x, y, rgb);
             }
         }
         // 绘制设置了RGB的新图片
         g2D.drawImage(bufferedImage, 0, 0, null);

         // 生成图片为PNG
         ImageIO.write(bufferedImage, "png", new File(outpath));
       //  MyLogger.logger.info("完成画图");

     }
     
     // 判断是背景还是内容
     public static boolean colorInRange(int color) {
         int red = (color & 0xff0000) >> 16;// 获取color(RGB)中R位
         int green = (color & 0x00ff00) >> 8;// 获取color(RGB)中G位
         int blue = (color & 0x0000ff);// 获取color(RGB)中B位
         // 通过RGB三分量来判断当前颜色是否在指定的颜色区间内
         if (red >= color_range && green >= color_range && blue >= color_range){
             return true;
         };
         return false;
     }
     
     //色差范围0~255
     public static int color_range = 210;
     
     
     
     
 	/**
 	 * @category txt转pdf
 	 * @param text+
 	 *            入参|txt文档全路径|{@link String}
 	 * @param pdf
 	 *            入参|paf全路径|{@link String}
 	 * @return 0 失败<br/>
 	 *         1 成功<br/>
 	 * @throws com.lowagie.text.DocumentException 
 	 */
 	@InParams(param = {
 			@Param(name = "text", comment = "txt文档全路径", type = String.class),
 			@Param(name = "pdf", comment = "paf全路径", type = String.class) })
 	@Returns(returns = { @Return(id = "0", desp = "失败"),
 			@Return(id = "1", desp = "成功") })
 	@Component(label = "txt转pdf", style = "判断型", type = "同步组件", comment = "txt转pdf", date = "2019-03-09 11:00:56")
	public static TCResult B_txt2pdf(String text, String pdf) {
 			Document document = new Document(PageSize.A4, 30, 30, 30, 30);
	try {
			OutputStream os = new FileOutputStream(new File(pdf));
			PdfWriter.getInstance(document, os);
			document.open();
			BaseFont bfChinese = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H", 
					BaseFont.NOT_EMBEDDED);
			InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(text)), "GBK");
			BufferedReader bufferedReader = new BufferedReader(isr);
			
			String str = "";
			String str1 = bufferedReader.readLine();
			int sum = str1.length();
			int split = str1.split("\\|", -1).length - 1;
			int g = 280 / (sum - split);
	if ((sum - split) > 279) {
			return TCResult.newFailureResult("0009", "表头无法放下这些字段");
			}
				int h = (int) Math.floor(g);
				Font FontChinese = new Font(bfChinese, h, Font.NORMAL);
				PdfPTable pdfTable = new PdfPTable(split + 1);
				PdfPCell pdfTableHeaderCell = new PdfPCell();
				pdfTableHeaderCell.setBackgroundColor(new Color(213, 141, 69));
				String s1[] = str1.split("\\|");
			for (String tableHeaderInfo : s1) {
				pdfTableHeaderCell.setPhrase(new Paragraph(tableHeaderInfo,FontChinese));
				pdfTable.addCell(pdfTableHeaderCell);
			}
				pdfTable.setWidthPercentage(100);
				pdfTable.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
				PdfPCell pdfTableContentCell = new PdfPCell();
				pdfTableContentCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
				pdfTableContentCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
			while ((str = bufferedReader.readLine()) != null) {
				String s[] = str.split("\\|");
				for (String tableContentInfo : s) {
					pdfTableContentCell.setPhrase(new Paragraph(tableContentInfo, FontChinese));
					pdfTable.addCell(pdfTableContentCell);
				}
			}
				float x = document.getPageSize().getWidth() - 150;
				float y = document.getPageSize().getHeight() - 150;
			// Image image = Image.getInstance(imagePath);
			// image.scaleAbsolute(80, 80);
			// image.setAbsolutePosition(x, y);
				document.add(pdfTable);
			// document.add(image);

			} catch (IOException | DocumentException de) {
				de.printStackTrace();
					return TCResult.newFailureResult("0009", de.toString() + "生成PDF报错！");
			} finally {
				if (document != null) {
				document.close();
			}
		}
		return TCResult.newSuccessResult();
	}
 	
 	
 	
 	
 	
 	/**
 	 * @category 获取产品所有参数信息
 	 * @param productcode
 	 *            入参|产品代码|{@link String}
 	 * @param funccode
 	 *            入参|功能代码|{@link String}
 	 * @param run_cxt
 	 *            入参|当前运行容器|
 	 *            {@link cn.com.agree.afa.svc.javaengine.context.JavaDict}
 	 * @param ver
 	 *            入参|版本日期|{@link String}
 	 * @param area
 	 *            入参|适用区域|{@link String}
 	 * @return 0 失败<br/>
 	 *         1 成功<br/>
 	 */
 	@InParams(param = {
 			@Param(name = "productcode", comment = "产品代码", type = String.class),
 			@Param(name = "funccode", comment = "功能代码", type = String.class),
 			@Param(name = "run_cxt", comment = "当前运行容器", type = cn.com.agree.afa.svc.javaengine.context.JavaDict.class),
 			@Param(name = "ver", comment = "版本日期", type = String.class),
 			@Param(name = "area", comment = "适用区域", type = String.class) })
 	@Returns(returns = { @Return(id = "0", desp = "失败"),
 			@Return(id = "1", desp = "成功") })
 	@Component(label = "获取产品所有参数信息", style = "判断型", type = "同步组件", comment = "根据产品代码、功能代码获取产品设置的所有参数,放到输入容器中", author = "cai", date = "2016-01-04 09:52:24")	
 	public static TCResult B_PM_GetProductParams(String productcode,String funccode, JavaDict run_cxt,String ver,String area ) throws SQLException{
 		
 		//try {
 			if((ver == null && area == null)||(ver.equals("V1.0.020130818") && area.equals("PRD"))){
 				//输入类型合法性检查
 				if(!(productcode instanceof String))
 					return TCResult.newFailureResult("FBC001", "入参产品代码非字符串类型");
 					
 				if(!(funccode instanceof String))
 					return TCResult.newFailureResult("FBC001", "入参功能代码非字符串类型");
 					
 				if(!(run_cxt instanceof JavaDict))
 					return TCResult.newFailureResult("FBC001", "入参当前运行容器非字典类型");
 					
 				
 				JavaDict product_cxt = new JavaDict("productcode" , productcode, "funccode" , funccode);
 				
 				Connection DBConn = DBConnProvider.getConnection();
 				String sql_str = "select  paramkeyname, paramvalue from t_pssm_parambook  where productcode = '"+ productcode +"'and funccode = '"+ funccode +"'";
 				AppLogger.info(sql_str);
 				
 				TCResult result = P_DataBase.P_DB_DMLSel(sql_str, 0, null, null);

 				if(result.getStatus()==0){
 					return TCResult.newFailureResult("FBD999",result.getErrorMsg());
 				}else if(result.getStatus()==2){
 					return TCResult.newSuccessResult();
 				}	
 				else{
 					Iterator<?> it = ((JavaList)result.getOutputParams().get(1)).iterator();
 					
 					while(it.hasNext()){
 						JavaList item = (JavaList) it.next();
 						run_cxt.setItem(((JavaList)item).get(0), ((JavaList)item).get(1));
 					}
 				}
 				return TCResult.newSuccessResult();
 			}
 			else
 				return TCResult.newFailureResult("FBC000", "版本日期或适用区域错误,请联系版本管理员");
 	}
 
}
